<?php

/**
 * Sort - page -search State 
 */
class SpsState {

    private static $prefix;

    public static function setPrefix($prefix) {
        self::$prefix = ucfirst($prefix);
    }

    public static function writeState($searchKey = '') {
        $prefix = self::$prefix;
        $state  = array();

        if ($prefix != '') {
            //pager
            $attribute     = $prefix . '_page';
            if (isset($_GET[$attribute]))
                $state['page'] = $_GET[$attribute] - 1;

            //sorting
            $attribute = 'sort';
            if (isset($_GET[$attribute])) {
                $sSort = $_GET[$attribute];
                $pos   = strpos($sSort, '.');

                if ($pos !== FALSE) {
                    $key           = substr($sSort, 0, $pos);
                    $state['sort'] = array($key           => true);
                }
                else
                    $state['sort'] = array($sSort         => false);
            }
            elseif (self::hasState('sort'))
                $state['sort'] = self::getState('sort');

            //search
            if ($searchKey == '')
                $searchKey = self::$prefix;
            if (isset($_GET[$searchKey]))
                $state['search'] = $_GET[$searchKey];
            elseif (self::hasState('search'))
                $state['search'] = self::getState('search');

            Yii::app()->user->setState($prefix, $state);
            return true;
        }
        else
            return false;
    }

    public static function clearState() {
        Yii::app()->user->setState(self::$prefix, null);
        return true;
    }

    public static function getState($key = '') {
        if (self::hasState($key)) {
            $state = Yii::app()->user->getState(self::$prefix);
            if ($key != '') {
                if (isset($state[$key]))
                    return $state[$key];
                else
                    return null;
            }
            else
                return $state;
        }
        else
            return null;
    }

    public static function hasState($key = '') {
        if ($key == '')
            return Yii::app()->user->hasState(self::$prefix);
        else {
            $state = Yii::app()->user->getState(self::$prefix);
            if (isset($state[$key]))
                return true;
            else
                return false;
        }
    }

}
